package com.dykj.fireFighting.web.base.enterprise.controller;

import java.util.*;

import com.dykj.fireFighting.api.base.enterprise.dto.SafePersonDto;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.entity.SafePerson;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.enterprise.service.ISafePersonService;
import com.dykj.fireFighting.api.base.enterprise.vo.SafePersonVo;
import com.dykj.fireFighting.api.base.system.entity.SysDirectory;
import com.dykj.fireFighting.api.base.system.service.ISysDirectoryService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.dto.CommonDto;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;



/**
 * 人员信息接口
 *
 * @Author JacksonTu
 * @Date  2021-06-24 14:58:26
 */
@Slf4j
@Api(value = "人员信息接口", tags = {"人员信息接口"})
@RestController
@RequestMapping("enterprise/safePerson")
public class SafePersonController {

    @DubboReference
    private ISafePersonService safePersonService;

    @DubboReference
    private IEnterpriseService enterpriseService;

    @DubboReference
    private ISysDirectoryService sysDirectoryService;

    /**
     * 获取登录用户的单位（监控中心）id
     */
    public Long getEnterpriseId() {
        try {
            Long enterpriseId = ShiroUtil.getUser().getEnterpriseId();
            return enterpriseId;
        }catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("请登录");
        }
    }

    /**
     * 获取单位信息
     */
    public Enterprise getEnterprise() {
        Enterprise enterprise = enterpriseService.getById(getEnterpriseId());
        return enterprise;
    }

    @AutoLog(value = "人员架构-人员架构")
    @ApiOperation(value = "人员架构", notes = "人员架构")
    @GetMapping("/person")
    public CommonResult<Enterprise> getPersonStructure() {
        // 当前单位信息 (顶级)
        Enterprise enterprise = getEnterprise();
        // 获取所有area_code
        List<SysDirectory> byParentCode = sysDirectoryService.getByParentCode(enterprise.getAreaCode());
        ArrayList<String> areaList = new ArrayList<>();
        for (SysDirectory code : byParentCode) {
            areaList.add(code.getCode());
        }
        // 获取当前下面所有社会单位
        List<Enterprise> unitList = enterpriseService.queryUnitList(enterprise.getBindingCode());
        // 获取当前下面所有监控中心
        List<Enterprise> centerList = enterpriseService.getAllCenter(areaList);
        // 监控中心存在
        if (centerList != null && centerList.size() > 0) {
            // 查询监控中心下所有社会单位并放入
            for (Enterprise center : centerList) {
                List<Enterprise> units = enterpriseService.queryUnitSelect(center.getId() + "");
                center.setChildren(units);
            }
            // 合并children
            unitList.addAll(centerList);
        }
        // 顶级加入子级信息
        enterprise.setChildren(unitList);
        return CommonResult.success(enterprise);
    }


    /**
     * 人员信息列表
     *
     * @return
     */
    @AutoLog(value = "人员信息-分页列表查询")
    @ApiOperation(value = "人员信息分页列表", notes = "人员信息分页列表")
    @GetMapping("/list")
    @RequiresPermissions("enterprise/enterpriseJob/list")
    public CommonResult<PageVo<SafePersonVo>> treeGrid(SafePersonDto commonDto) {
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        commonDto.setUnitId(loginUserVo.getEnterpriseId().toString());
        PageVo<SafePersonVo> page = safePersonService.queryList(commonDto);
        return CommonResult.success(page);
    }

    /**
     * 获取人员信息信息
     */
    @AutoLog(value = "人员信息-获取人员信息信息")
    @ApiOperation(value = "获取人员信息信息", notes = "获取人员信息信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
    public CommonResult<SafePersonVo> info(@PathVariable("id") String id){
        SafePersonVo safePersonVo = safePersonService.getInfoById(id);
        return CommonResult.success(safePersonVo);
    }

    /**
     * 保存人员信息信息
     */
    @AutoLog(value = "人员信息-保存人员信息信息")
    @ApiOperation(value = "保存人员信息信息", notes = "保存人员信息信息")
    @PostMapping("/save")
    @RequiresPermissions("enterprise/enterpriseJob/save")
    public CommonResult save(@Valid @RequestBody SafePerson safePerson) {
        try {
            LoginUserVo loginUserVo = ShiroUtil.getUser();
            safePerson.setUnitId(loginUserVo.getEnterpriseId().toString());
            safePerson.setCreateTime(new Date());
            safePerson.setUpdateTime(new Date());
                safePersonService.save(safePerson);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改人员信息信息
     */
    @AutoLog(value = "人员信息-修改人员信息信息")
    @ApiOperation(value = "修改人员信息信息", notes = "修改人员信息信息")
    @PostMapping("/update")
    @RequiresPermissions("enterprise/enterpriseJob/update")
    public CommonResult update(@Valid @RequestBody SafePerson safePerson) {
        try {
            safePerson.setUpdateTime(new Date());
                safePersonService.updateById(safePerson);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除人员信息信息
     */
    @AutoLog(value = "人员信息-删除人员信息信息")
    @ApiOperation(value = "删除人员信息信息", notes = "删除人员信息信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
    @RequiresPermissions("enterprise/enterpriseJob/delete")
    public CommonResult delete(@RequestBody String[]ids) {
        try {
                safePersonService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }
}
